package com.victor9ac.tfm.rest.connector;

import java.io.IOException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;

import org.apache.http.client.ClientProtocolException;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

/**
 * 
 * 
 * Jersey approach
 * 
 * @see http://stackoverflow.com/questions/15214252/is-jersey-rest-client-more-optimal-than-httpclient-for-calling-a-restful-service
 * @see http://blogs.atlassian.com/2013/07/http-client-performance-io/
 * 
 * HTTP approach
 * 
 * @see http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-apache-httpclient/
 */
public class RestClientJerseyConnectorHelloWorld 
{
	public static void main(String[] args) throws ClientProtocolException, IOException {
		  
			requestTestByGET();
		 }


	private static void requestTestByGET() {
		ClientConfig config = new DefaultClientConfig();
		
		Client client = Client.create(config);
		
		client.setConnectTimeout(2000);//ms
		client.setReadTimeout(3000);//ms like socket timeout
  
		WebResource service = client.resource(UriBuilder.fromUri("http://www.marca.com").build());
		// getting XML data
		Builder myRestWebService = service.path("restPath").path("resourcePath").accept(MediaType.APPLICATION_JSON);
		String result = myRestWebService.get(String.class);
		
		System.out.println(result);
		// getting JSON data
		System.out.println(service.path("restPath").path("resourcePath").accept(MediaType.APPLICATION_XML).get(String.class));

		//getting PLAIN TEXT
		System.out.println(service.path("restPath").path("resourcePath").accept(MediaType.TEXT_PLAIN).get(String.class));

	}

	
	public static void requestTestByPOST() {
		
			  ClientConfig config = new DefaultClientConfig();
			  Client client = Client.create(config);
			  
			  WebResource webResource = client.resource(UriBuilder.fromUri("http://my-rest-endpoint").build());
			  
			  MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
			  formData.add("name1", "val1");
			  formData.add("name2", "val2");
			  
			  ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
			  System.out.println("Response " + response.getEntity(String.class));
			 
	}
	
	
}
